//
//  KKComposeView.swift
//  KKWeibo
//
//  Created by kassia on 16/7/20.
//  Copyright © 2016年 kassia. All rights reserved.
//

import UIKit
import pop

class KKComposeView: UIView {

    // 创建目标控制器
    private var target: UIViewController?
    
    //  创建按钮的集合
    private lazy var composeTempButtons = [KKComposeButton]()
    
    // 懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenshot().applyExtraLightEffect())
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
       backgroundColor = RandomColor()
        
        // 设置frame
       self.frame = CGRectMake(0, 0, screenWidth, screenHeight)
        
        addSubview(bgImageView)
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
    
        addChildButton() // 添加子控件
    }

    // 读取plist文件
    private func loadComposePlist() -> [KKComposeMenu] {
    
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        let composeDitArray = NSArray(contentsOfFile: path)!
        
        // 定义可变数组
        var tempArray = [KKComposeMenu]()
        
        for dict in composeDitArray {
        
            let composeMenu = KKComposeMenu(dict: dict as! [String : AnyObject])
        
            tempArray.append(composeMenu)
        }
        
            return tempArray
    }
    
    // 添加子按钮
    private func addChildButton() {
        // 按钮的宽度
        let buttonWidth: CGFloat = 80
        // 按钮的高度
        let buttonHeight: CGFloat = 110
        // 按钮之间的间距
        let itemMargin: CGFloat = (weight - 3 * buttonWidth) / 4
        // 获取plist里面的数据
        let composeMenuArray = loadComposePlist()
        
        for (i,value) in composeMenuArray.enumerate() {
        
            let button = KKComposeButton()
            
            // 给button 的属性赋值
            button.composeMenu = value
            
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            
            // 添加点击事件
            button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
            
            // 计算行的索引
            let colIndex = i % 3
            
            // 计算列的索引
            let rowIndex = i / 3
            
            // 计算x坐标
            button.x = buttonWidth * CGFloat(colIndex) + itemMargin * CGFloat((colIndex + 1))
            
            // 计算y坐标
            button.y = buttonHeight * CGFloat(rowIndex) + itemMargin * CGFloat((rowIndex + 1)) + screenHeight
            
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            
            button.setTitle(value.title, forState: .Normal)
            
            composeTempButtons.append(button) // 添加到按钮数组
            
            addSubview(button)

        }
    }
    
    // pop 动画
    func show(target: UIViewController) {
   
        self.target = target
        
        target.view.addSubview(self) // 将自己添加当目标控制器
        
        for (i,value) in composeTempButtons.enumerate() {
        
           startAnimation(value, i: i, isUp: true)
        }
        
    }
    
    // 开启pop动画
    private func startAnimation(value: UIButton,i: Int, isUp: Bool) {
    
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        // 动画执行的目的地
        let y = isUp ? value.centerY - 350 : value.centerY + 350
        
        animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: y))
        
        // 设置弹簧效果
        animation.springBounciness = 5
        
        // 抖动速度
        animation.springSpeed = 10
        
        // 开始动画时间
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
        
        // 执行动画
        value.pop_addAnimation(animation, forKey: nil)
    
    }
    
    /*
        按钮点击事件
     */
    
    @objc private func buttonAction(btn: KKComposeButton) {
    
        UIView.animateWithDuration(0.25, animations: { () -> Void in
        
            for value in self.composeTempButtons {
            
                value.alpha = 0.2
                if value == btn {
                
                    // 点击放大
                    value.transform = CGAffineTransformMakeScale(1.5, 1.5)
                
                } else {
                 
                    // 缩小
                    value.transform = CGAffineTransformMakeScale(0.6, 0.6)
                
                }
            
            }
            
            }) { (_) -> Void in
               
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    for value in self.composeTempButtons {
                    
                        value.alpha = 1
                        
                        // 回到最初状态
                        value.transform = CGAffineTransformIdentity
                    
                    }
                    
                    }, completion: { (_) -> Void in
                        
                        // 指定类型
                        let classType = NSClassFromString(btn.composeMenu!.className!) as! UIViewController.Type
                        
                        // 创建指定类型
                        let vc = classType.init()
                        
                        vc.title = "发微博"
                        let nav = UINavigationController(rootViewController: vc)
                        
                        self.target!.presentViewController(nav, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                            
                        })
                        
                        
                })
                
        }
    
    
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        removeFromSuperview()
    }
}
